import React, { useState, useEffect, useCallback } from 'react';
import { List,Input } from 'react-vant'
import { Toast,CenterPopup, Button} from 'antd-mobile'
import { useLocation } from 'react-router-dom';
import Loading from '@/components/Loading';
import HeadTop from '@/components/HeadTop';
import CapTabs from '@/components/CapTabs'
import ListItem from '@/components/ListItemCheck';
import FooterCheck from '@/components/FooterCheck/index'
import PickerSelect from '@/components/PickerSelect';
import { menuTab, listFields, listdata } from './const';
import './index.less'
import ApiIndexd from '@/api/equipment.js';
import ApiIndex from '@/api/approve.js';
import { updateStatusList, getStatusList } from "./const";

const Index = ({ history }) => {
    const [list, setList] = useState([]);
    const [statusList, setStatusList] = useState(getStatusList());
    const [loading, setLoading] = useState(false);
    const [finished, setFinished] = useState(false);
    const [activeTab, setactiveTab] = useState('2')  //tab切换
    const [isAllcheck, setisAllcheck] = useState(false); // 全选状态
    const [inputvalue, setinputvalue] = useState('');
    const [gongSquier, setGongSquier] = useState([]);
    const [factoryArea, setfactoryArea] = useState('');
    const [shiftType, setshiftType] = useState('');
    const location = useLocation();
    const [selectedIds, setSelectedIds] = useState([])
    const [visible, setVisible] = useState(false)
    const title = new URLSearchParams(location.search).get('title');

    const [basicColumns, setbasicColumns] = useState([
        [
            { label: '白班', value: '白班' },
            { label: '夜班', value: '夜班' },
        ],
    ]); 


    useEffect(() => {
        getRequestData()
        getDic()
        getDicRealt()
    }, [activeTab])

    const getRequestData = async (area = factoryArea, shift = shiftType) => {
        setLoading(true)
        let params = {
            page: 1,
            size: 9999,
            status: activeTab  == '1' ? 'WAIT_FINISH' : 'FINISH',
            type:'PATROL_INSPECTION',
            factoryArea: area || '',
            shiftType: shift || ''
        }
        let res = await ApiIndex.approvalDeviceInspectionRecord(params)
        setLoading(false)
        if (res.data.code) {
            Toast.show({
                content: '请求失败:' + res.data.msg,
            })
            return
        }
        let list = res.data.data.records
        const newList = list.map(el => ({ ...el, check: false }));
        setList(newList)
        setFinished(true);
        setLoading(false)
        setSelectedIds([])

    }

    const getDic = () => {
        ApiIndexd.dictDetailsList({ code: 'FACTORY_AREA' }).then(res => {
            if (res.data.code == 0) {
                setGongSquier([res.data.data])
            }
        })
    }
    const getDicRealt = () => {
        ApiIndexd.dictDetailsList({ code:'INSPECTION_RESULT' }).then(res => {
            if (res.data.code == 0) {
                updateStatusList(res.data.data);
                setStatusList(getStatusList()); 
            }
        })
    }
    const setSelectValShift = (v) => {
        const shift = v[0];
        setshiftType(shift);
        getRequestData(factoryArea, shift);
    }
    const changTab = (i) => {
        // console.log(i,3322)
        setactiveTab(i)
        // getRequestData()
    }
    const confirmSubmit = () => {
        const newarr = selectedIds.map(item =>{
            return {
                no:item.no,
                cancelReason:inputvalue
            }
        })
        // console.log(newarr,33)
        ApiIndex.cancelBatch(newarr).then(res =>{
            if(res.data.success){
                setVisible(false)
                getRequestData()
                Toast.show({
                    content: '操作成功',
                })
            }
            
        })
    }
    const handleChange = (vl) =>{
        setinputvalue(vl)
  
    }
    const setSelectValSquer = (v) => {
        const area = v[0];
        setfactoryArea(area);
        getRequestData(area, shiftType); 
    }
    const handleSubmitBtn = (type) => {
        //取消
        if(activeTab == '1'){
            if(selectedIds.length > 0){
                setinputvalue('')
                setVisible(true)
                
            }else {
                Toast.show({
                    content: '请选择数据！',
                })
            }
        }else {
            let arr = selectedIds.map(item => item.no)
            ApiIndex.cancelConfirmBatch(arr.join(',')).then(res =>{
                if(res.data.success){
                    setSelectedIds([])
                    getRequestData()
                    Toast.show({
                        content: '操作成功',
                    })
                }else {
                    Toast.show({
                        content: res.data.msg,
                    })
                }
            })
        }
    }

    const getFooterButtons = () => {
        if (activeTab === '1') {
            return { cancelBtnTxt: '批量取消' };
        } else if (activeTab === '2') {
            return { sureBtnTxt: '批量确认' };
        }
        return {};
    };

    const itemHandleCheck = (item) => {
        // 更新列表项的选中状态
        const newList = list.map(el =>
            el.no === item.no ? { ...el, check: !el.check } : el
        );
        const newSelectedIds = newList.reduce((acc, currentItem) => {
            if (currentItem.check && currentItem.no === item.no) {
                return [...acc, currentItem];
            } else if (!currentItem.check && currentItem.no === item.no) {
                return acc.filter(item => item.no !== currentItem.no);
            }
            return acc;
        }, [...selectedIds]);
        
        setList(newList);
        setSelectedIds(newSelectedIds);
        // 更新全选状态
        const allChecked = newList.every(el => el.check);
        setisAllcheck(allChecked);
    }

    const handlesetAllcheck = (e) => {
        
        let newSelectedIds = []
        if(e){
             newSelectedIds = list.map(item => item)
        }else {
            newSelectedIds = []
        }
        setSelectedIds(newSelectedIds);
        const newList = list.map(el => ({ ...el, check: e }));
        setList(newList);
        setisAllcheck(e);
    };

    const setSelectVal = (v) => {
        console.log(v)
    }

    return (
        <div className='page-wrapper'>
            {
                loading ? <Loading></Loading> : null
            }
            <HeadTop
                title={title}
                history={history}
            ></HeadTop>
            <div className="select-pan">
            <PickerSelect
                    placeholderTxt="请选择工区"
                    basicColumns={gongSquier}
                    setSelectVal={(e) => setSelectValSquer(e)}
                ></PickerSelect>
                <div style={{ height: 6}}></div>
                <PickerSelect
                    placeholderTxt="请选择班次"
                    basicColumns={basicColumns}
                    setSelectVal={(e) => setSelectValShift(e)}
                ></PickerSelect>
            </div>
            {/* <CapTabs
                changTab={changTab}
                menus={menuTab}></CapTabs> */}
            <div className="page-body" style={{ padding: 15 }}>
                <List finished={finished} errorText='请求失败，点击重新加载'>
                    {
                        list.map(el => <ListItem
                            key={el.id}
                            item={el}
                            listFields={listFields}
                            emitCheck={itemHandleCheck}
                        ></ListItem>)
                    }
                    {finished ? <div className='loadingTxt'>无更多数据</div> : null}
                </List>
            </div>
            <FooterCheck
                hasCheck={true}
                {...getFooterButtons()}
                isAllcheck={isAllcheck}
                emitSetAllcheck={handlesetAllcheck}
                emitSubmitBtn={handleSubmitBtn}></FooterCheck>
                    <CenterPopup
                    visible={visible}
                    onMaskClick={() => {
                    setVisible(false)
                    }}
                >
                    <div className='warp-dia'>
            
                    <div className="select-name-item">取消原因</div>
                    <Input.TextArea
                        value={inputvalue}
                        onChange={handleChange}
                        style={{ border: '1px solid #41AEE3', }}
                        placeholder="请输入审批原因"
                        autoSize={{ minHeight: 80, maxHeight: 120 }}
                        />
                        <div className="btn-c">
                            <Button size="large" color="#40AFE6" style={{
                                '--background-color': "#40AFE6",
                                width: 80
                            }} onClick={confirmSubmit}>确定</Button>

                        </div>
                    </div>
                </CenterPopup>
        </div>
    );
}

export default Index;
